package config

import (
	"sell_data_system/servicer/common"
	"fmt"
	"errors"
	"time"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	)


//DataBaseInfo 数据库连接行信息
type DataBaseInfo struct {
	UserName string //用户名
    Password string //密码
    Host string //ip
    Port string // 端口号
    DBName string // 数据库名称
}
type BaseModel struct {
	ID        uint `gorm:"primary_key;AUTO_INCREMENT"`
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt *time.Time `sql:"index"`
}

//CreateUrl 拼接数据库连接路径 like user:password@tcp(host:port)/dbname?charset=utf8&parseTime=True&loc=Local
func (info *DataBaseInfo) CreateUrl() (string ,error) {
	if common.Isblank(info.DBName) {
		return "",errors.New("no database name")
	}
	if common.Isblank(info.UserName) {
		return "",errors.New("no database username")
	}
	if common.Isblank(info.Password) {
		return "",errors.New("no database password")
	}
	host := info.Host
	if common.Isblank(host) {
		host="localhost"
	}
	port := info.Port
	if common.Isblank(port) {
		port = "3306"
	}
	//user:password@tcp(host:port)/dbname?charset=utf8&parseTime=True&loc=Local
	return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",info.UserName,info.Password,host,port,info.DBName),nil
}
//CreateConnection 创建连接
func CreateConnection(info *DataBaseInfo) (*gorm.DB,error)   {
	if dburl,err :=  info.CreateUrl(); err != nil {
		fmt.Printf("连接数据库错误：%s \n",err.Error())
		return nil ,err
	} else {
		fmt.Println(dburl)
		return  gorm.Open("mysql",dburl)
	}

}
